package edu.nf.ch01.service;

import edu.nf.ch01.entity.User;
import edu.nf.ch01.mapper.UserMapper;
import edu.nf.ch01.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * @author CSY
 * @date 2025 - 04 - 22
 */
public class UserService {
    public void saveUser(User user){
        //创建SqlSession实例
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            //创建UserMapper接口的代理对象
            //这个代理对象会解析并执行mapper映射配置文件中的sql
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            //执行代理对象的save方法
            mapper.saveUser(user);
            //事务提交
            sqlSession.commit();
        }catch (RuntimeException e){
            //报错事务回滚
            sqlSession.rollback();
        }finally {
            //关闭SqlSession
            sqlSession.close();
        }
    }

    public void updateUser(User user){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            mapper.updateUser(user);
            sqlSession.commit();
        }catch (RuntimeException e){
            sqlSession.rollback();
        }finally {
            sqlSession.close();
        }
    }

    public void deleteUser(Integer id){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            mapper.deleteUser(id);
            sqlSession.commit();
        }catch (RuntimeException e){
            sqlSession.rollback();
        }finally {
            sqlSession.close();
        }
    }

    public List<User> findAllUsers(){
        List<User> users = null;
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try{
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            users = mapper.findAllUsers();
        }finally {
            sqlSession.close();
        }
        return users;
    }
}
